<html>
<html>
<head>
    <title>Resultados</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<?php
require 'functions.php';

$ZONASQUERY = "SELECT zona.`zona_id` FROM `zona`";
$ZONAS = sqlQueryToDB($ZONASQUERY);
$CONDITION = "";
$CONDITION_IS = "";
$CONDITION_ISNOT =" maquina.`maquina_id` NOT IN (select maquina.`maquina_id`
                                     from maquina
                                       inner join maquinacliente on maquinacliente.`maquina_id`=maquina.`maquina_id`
                                       inner join cliente on maquinacliente.`cliente_id`=cliente.`cliente_id`
                                       inner join zona on zona.`zona_id`=cliente.`zona_id`
                                     WHERE";
$QUERY = "SELECT DISTINCT maquina.`nombre` AS Maquina, maquina.`marca` AS Marca FROM maquina ";

$COUNTER_IS = 0;
$COUNTER_ISNOT = 0;

while($ROWS = mysqli_fetch_row($ZONAS)){
    foreach($ROWS as $ITEM){
        $CHECK_IS_I = "check_is_".$ITEM;
        $CHECK_ISNOT_I = "check_isNot_".$ITEM;
        if(isset($_GET[$CHECK_IS_I])){
            $CONDITION_IS .= " maquina.`maquina_id` IN (select maquina.`maquina_id`
                                     from maquina
                                       inner join maquinacliente on maquinacliente.`maquina_id`=maquina.`maquina_id`
                                       inner join cliente on maquinacliente.`cliente_id`=cliente.`cliente_id`
                                       inner join zona on zona.`zona_id`=cliente.`zona_id`
                                     where zona.`zona_id`= ".$ITEM.") AND ";
            $COUNTER_IS+=1;
        }
        if(isset($_GET[$CHECK_ISNOT_I])){
            $CONDITION_ISNOT .= " zona.`zona_id`= (".$ITEM.") OR ";
            $COUNTER_ISNOT+=1;
        }
    }
}
$CONDITION_IS = trim($CONDITION_IS, " AND ");
$CONDITION_ISNOT = trim($CONDITION_ISNOT, "OR ");


if ($COUNTER_IS > 0 OR $COUNTER_ISNOT > 0) {
    $CONDITION .= " WHERE ";

    if ($COUNTER_IS > 0) {
        $CONDITION .= $CONDITION_IS;
    }

    if ($COUNTER_IS > 0 AND $COUNTER_ISNOT > 0) {
        $CONDITION .= " AND ";
    }

    if ($COUNTER_ISNOT > 0) {
        $CONDITION .= $CONDITION_ISNOT.")";
    }
}

$QUERY  .= $CONDITION." GROUP BY maquina.`maquina_id`";

sqlQueryPrettyParser($QUERY);

/*Efectua la consulta*/
$DATA = sqlQueryToDB($QUERY);

/*Muestra la tabla de resultados*/
if ($DATA->num_rows < 1) {
    echo "No hay resultados para armar una tabla<br><br>";
} else {
    echo sqlDataToHtmlTable($DATA);
}
?>
<br>
<input type="button" onclick="history.back()" name="Regresar" value="Regresar">
</body>
</html>
